<template>
  <div class="role-management-container">
    <div class="page-header">
      <el-button type="primary" @click="navigateToRole">
        <el-icon>
          <ArrowLeft />
        </el-icon>
        返回
      </el-button>
      <h1>角色列表</h1>
      <el-button type="primary" @click="navigateToAddRole">
        <el-icon>
          <Plus />
        </el-icon>
        添加角色
      </el-button>
    </div>

    <!-- 搜索区域 -->
    <div class="search-container">
      <el-input v-model="searchQuery" placeholder="搜索角色名称或描述" class="search-input" @keyup.enter="fetchRoles" />
      <el-button @click="fetchRoles" class="search-button">
        <el-icon>
          <Search />
        </el-icon>

        搜索</el-button>
      <el-button @click="resetSearch" class="reset-button">重置</el-button>
    </div>

    <!-- 角色列表 -->
    <el-table v-loading="loading" :data="filteredRoles" border class="role-table" stripe>
      <el-table-column type="index" label="序号" width="80" align="center" />
      <el-table-column prop="name" label="角色名称" min-width="150" />
      <el-table-column prop="description" label="角色描述" min-width="200" />
      <el-table-column label="权限数量" width="120" align="center">
        <template #default="scope">{{ scope.row.permissions.length }}</template>
      </el-table-column>
      <el-table-column prop="createdAt" label="创建时间" width="180" />
      <el-table-column prop="updatedAt" label="更新时间" width="180" />
      <el-table-column prop="isActive" label="是否激活" width="120" align="center">
        <template #default="scope">
          <el-switch v-model="scope.row.isActive" @change="handleStatusChange(scope.row)" />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" align="center">
        <template #default="scope">
          <el-button size="small" type="primary" @click="openEditDialog(scope.row)" :disabled="isSuperAdmin(scope.row)">
            <el-icon>
              <Edit />
            </el-icon>
            编辑
          </el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.row)" :disabled="isSuperAdmin(scope.row)">
            <el-icon>
              <Delete />
            </el-icon>
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页控件 -->
    <div class="pagination-container">
      <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :total="totalRoles"
        :page-sizes="[5, 10, 20, 50]" layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />
    </div>

    <!-- 编辑角色对话框 -->
    <el-dialog v-model="dialogVisible" :title="isEditMode ? '编辑角色' : '添加角色'" :width="'600px'"
      :close-on-click-modal="false">
      <el-form ref="roleFormRef" :model="roleForm" :rules="formRules" status-icon label-width="100px">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleForm.name" placeholder="请输入角色名称" :disabled="isEditMode && isSuperAdmin(roleForm)" />
        </el-form-item>

        <el-form-item label="角色描述" prop="description">
          <el-input v-model="roleForm.description" placeholder="请输入角色描述" type="textarea" :rows="3" />
        </el-form-item>

        <el-form-item label="权限分配" prop="permissions">
          <el-checkbox-group v-model="roleForm.permissions">
            <div class="permission-groups">
              <div class="permission-group" v-for="group in permissionGroups" :key="group.id">
                <div class="permission-group-label">{{ group.label }}</div>
                <div class="permission-options">
                  <el-checkbox v-for="perm in group.permissions" :key="perm.value" :label="perm.value"
                    :disabled="isEditMode && isSuperAdmin(roleForm)">
                    {{ perm.label }}
                  </el-checkbox>
                </div>
              </div>
            </div>
          </el-checkbox-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleFormSubmit" :loading="submitLoading">
          {{ isEditMode ? '更新' : '创建' }}
        </el-button>
      </template>
    </el-dialog>

    <!-- 删除确认对话框 -->
    <el-dialog v-model="deleteDialogVisible" title="确认删除" :width="'400px'" :close-on-click-modal="false">
      <div class="delete-warning">
        <p>确定要删除角色 <strong>{{ currentRole.name }}</strong> 吗？</p>
        <p v-if="roleInUse">此角色当前有用户正在使用，删除可能导致相关用户无法正常访问系统。</p>
      </div>
      <template #footer>
        <el-button @click="deleteDialogVisible = false">取消</el-button>
        <el-button type="danger" @click="confirmDelete()">确认删除</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, nextTick } from 'vue';
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';
import { Plus, Search, Edit, Delete, ArrowLeft } from '@element-plus/icons-vue';
import { rolenameRules,descriptionRules,permissionRules } from '../utils/validationRules';

const router = useRouter();

// 状态变量
const loading = ref(false);
const submitLoading = ref(false);
const dialogVisible = ref(false);
const deleteDialogVisible = ref(false);
const isEditMode = ref(false);
const searchQuery = ref('');
const currentPage = ref(1);
const pageSize = ref(10);
const totalRoles = ref(0);
const roleFormRef = ref(null);
const currentRole = ref(null);
const roleInUse = ref(false);

// 权限组数据 - 按业务领域分组
const permissionGroups = ref([
  {
    id: 'user',
    label: '用户管理',
    permissions: [
      { value: 'user:read', label: '查看用户' },
      { value: 'user:create', label: '创建用户' },
      { value: 'user:update', label: '编辑用户' },
      { value: 'user:delete', label: '删除用户' },
    ],
  },
  {
    id: 'role',
    label: '角色管理',
    permissions: [
      { value: 'role:read', label: '查看角色' },
      { value: 'role:create', label: '创建角色' },
      { value: 'role:update', label: '编辑角色' },
      { value: 'role:delete', label: '删除角色' },
    ],
  },
  {
    id: 'system',
    label: '系统设置',
    permissions: [
      { value: 'dashboard:view', label: '查看仪表盘' },
      { value: 'setting:read', label: '查看设置' },
      { value: 'setting:update', label: '更新设置' },
      { value: 'log:view', label: '查看日志' },
    ],
  },
]);

// 所有权限列表（扁平化）
const allPermissions = computed(() => {
  return permissionGroups.value.reduce((acc, group) => {
    return [...acc, ...group.permissions];
  }, []);
});

// 角色列表数据
const roles = ref([
  {
    id: 1,
    name: 'SuperAdmin',
    description: '超级管理员，拥有系统所有权限',
    permissions: allPermissions.value.map(p => p.value),
    createdAt: '2023-01-01',
    updatedAt: '2023-01-01',
    isActive: true
  },
  {
    id: 2,
    name: 'Admin',
    description: '系统管理员，拥有大部分管理权限',
    permissions: allPermissions.value
      .filter(p => p.value !== 'role:delete' && p.value !== 'user:delete')
      .map(p => p.value),
    createdAt: '2023-01-10',
  },
  {
    id: 3,
    name: 'Editor',
    description: '内容编辑，拥有内容管理权限',
    permissions: ['user:read', 'dashboard:view', 'log:view'],
    createdAt: '2023-02-15',
  },
]);

totalRoles.value = roles.value.length;

// 搜索过滤后的角色列表
const filteredRoles = computed(() => {
  if (!searchQuery.value) {
    return roles.value;
  }
  const query = searchQuery.value.toLowerCase();
  return roles.value.filter(role =>
    role.name.toLowerCase().includes(query) ||
    (role.description && role.description.toLowerCase().includes(query))
  );
});

// 角色表单数据
const roleForm = ref({
  name: '',
  description: '',
  permissions: [],
});

const formRules ={
  name: [
    rolenameRules,
    { validator: checkRoleNameUnique, trigger: 'blur' },
  ],
  description:descriptionRules,
  permission:permissionRules
}
// 检查角色名称唯一性
function checkRoleNameUnique(rule, value, callback) {
  if (!value) {
    callback();
    return;
  }

  // 编辑模式下不检查当前角色名称
  if (isEditMode.value && roleForm.value.id) {
    const originalRole = roles.value.find(r => r.id === roleForm.value.id);
    if (originalRole && originalRole.name === value) {
      callback();
      return;
    }
  }

  // 检查是否已存在同名角色
  const exists = roles.value.some(role => role.name === value);
  if (exists) {
    callback(new Error('角色名称已存在，请使用其他名称'));
  } else {
    callback();
  }
}

// 判断是否为超级管理员
function isSuperAdmin(role) {
  return role && role.name === 'SuperAdmin';
}

// 检查角色是否被用户使用
async function checkRoleInUse(roleId) {
  // 模拟API调用检查角色是否被使用
  return new Promise(resolve => {
    setTimeout(() => {
      // 模拟SuperAdmin和Admin角色被使用
      resolve([1, 2].includes(roleId));
    }, 500);
  });
}

// 获取角色列表数据
function fetchRoles() {
  loading.value = true;
  // 模拟API调用
  setTimeout(() => {
    totalRoles.value = filteredRoles.value.length;
    loading.value = false;
  }, 500);
}

// 重置搜索
function resetSearch() {
  searchQuery.value = '';
  currentPage.value = 1;
  fetchRoles();
}

// 打开创建角色对话框
function openCreateDialog() {
  isEditMode.value = false;
  roleForm.value = {
    name: '',
    description: '',
    permissions: [],
  };
  nextTick(() => {
    roleFormRef.value && roleFormRef.value.resetFields();
  });
  dialogVisible.value = true;
}

// 打开编辑角色对话框
function openEditDialog(role) {
  isEditMode.value = true;
  currentRole.value = { ...role };
  roleForm.value = {
    id: role.id,
    name: role.name,
    description: role.description,
    permissions: [...role.permissions],
  };
  dialogVisible.value = true;
}

// 提交表单（创建/更新角色）
async function handleFormSubmit() {
  try {
    await roleFormRef.value.validate();
    submitLoading.value = true;

    if (isEditMode.value) {
      // 更新角色
      await updateRole();
    // } else {
    //   // 创建新角色
    //   await createRole();
    }

    dialogVisible.value = true;
    ElMessage.success(`${isEditMode.value ? '更新' : '创建'}角色成功`);
    dialogVisible.value = false;
    fetchRoles();
  } catch (error) {
    console.error('表单提交失败:', error);
    ElMessage.error('操作失败，请重试');
  } finally {
    submitLoading.value = false;
  }
}

// 创建新角色
// function createRole() {
//   return new Promise(resolve => {
//     setTimeout(() => {
//       const newRole = {
//         id: Math.max(...roles.value.map(r => r.id)) + 1,
//         name: roleForm.value.name,
//         description: roleForm.value.description,
//         permissions: [...roleForm.value.permissions],
//         createdAt: new Date().toISOString().split('T')[0],
//       };
//       roles.value.push(newRole);
//       resolve();
//     }, 800);
//   });
// }

// 更新角色
function updateRole() {
  return new Promise(resolve => {
    setTimeout(() => {
      const index = roles.value.findIndex(r => r.id === roleForm.value.id);
      if (index !== -1) {
        // 超级管理员角色始终拥有全部权限
        const permissions = isSuperAdmin(roleForm.value)
          ? allPermissions.value.map(p => p.value)
          : roleForm.value.permissions;

        roles.value[index] = {
          ...roles.value[index],
          name: roleForm.value.name,
          description: roleForm.value.description,
          permissions: permissions,
        };
      }
      resolve();
    }, 800);
  });
}

// 打开删除确认对话框
async function handleDelete(role) {
  if (isSuperAdmin(role)) {
    ElMessage.warning('超级管理员角色不能删除');
    return;
  }

  currentRole.value = role;
  roleInUse.value = await checkRoleInUse(role.id);
  deleteDialogVisible.value = true;
}

// 确认删除角色
async function confirmDelete() {
  try {
    // 模拟API调用删除角色
    await new Promise(resolve => {
      setTimeout(() => {
        roles.value = roles.value.filter(r => r.id !== currentRole.value.id);
        resolve();
      }, 800);
    });

    ElMessage.success('角色删除成功');
    deleteDialogVisible.value = false;
    fetchRoles();
  } catch (error) {
    ElMessage.error('角色删除失败，请重试');
  }
}

// 处理角色激活状态变更
function handleStatusChange(role) {
  role.updatedAt = new Date().toISOString().split('T')[0];
  ElMessage.success(`角色更新`);
}

// 分页大小变化
function handleSizeChange(val) {
  pageSize.value = val;
  currentPage.value = 1;
  fetchRoles();
}

// 当前页码变化
function handleCurrentChange(val) {
  currentPage.value = val;
  fetchRoles();
}

// 页面加载时获取数据
onMounted(() => {
  fetchRoles();
});
function navigateToAddRole() {
  router.push('/roles/add');
}
function navigateToRole() {
  router.push('/roles');
}
</script>
<style scoped>
@import url('../styles/rolelist.css');
</style>